/**
 * 背景：
 *    现在整个rn项目打包后，jsbundle体积有3.2M，后续版本迭代后，体积将更大。
 *
 * 功能：
 *    将jsbundle文件分割为2个文件，第一个文件是入口相关的代码，例如基础库、首页等，
 *    第2个文件是其它页面，如活动页、结算页、收银台、订单详情，等不需要已进入时就加载的代码。
 */
const file = require('../common/file');
const path = require('path');
let acorn = require('../common/acorn.js');
const match_pages_file = require('./match_pages_file');
const is__d_call = require('./is__d_call');
const get_define_number = require('./get_define_number');
const parse_pages_from_pages_file = require('./parse_pages_from_pages_file');
const get_dependencies_list_in___d_call = require('./get_dependencies_list_in___d_call');
const spawnSync = require('child_process').spawnSync;
const color = require('../common/colors-cli/lib/index.js');
const utility = require('../common/utility.js');
const replace_bundle_folder_for_print = utility.replace_bundle_folder_for_print;
const write_comment_file = utility.write_comment_file;
const count__d_call_percentage = require('./count__d_call_percentage.js');

// 重要： todo ： 收集所有与预期不一致的结构，并输出，打包压缩时需检查所有内容，或如果存在不一致预期，直接终止拆包

// 判断是jdreact-core-lib.common.js文件
// t.JDModal=D(a[2]),
function is_jdreact_core_lib_common_file(ast,jsbundle_code) {
	const start = ast.start;
	const end = ast.end;
	const code = jsbundle_code.substring(start,end);
	const m = code.match(/\b[a-zA-Z0-9\_]+\.JD[a-zA-Z0-9\_]+\s*\=\s*[a-zA-Z0-9\_]+\(\s*[a-zA-Z0-9\_]+\[\d+\]\)\,/g);
	if(m&&m.length>20){
		let widget_array = [];
		const len = m.length;
		for(let i=0; i<len; i++){
			const itm_string = m[i];
			const mm = itm_string.match(/\.(JD[a-zA-Z0-9\_]+)\s*\=\s*[^\d]+(\d+)[^\d]+/);
			if(!mm){
				return false;
			}
			widget_array.push({
				code:itm_string,
				name:mm[1],
				dependNumberInArray:parseInt(mm[2],10)
			});
		}
		return widget_array;
	}
}

/*get JDImage() {
 return t(u[0])
 }, get JDButton() {
 return t(u[1])
 }, get JDTouchable() {
 return t(u[2])
 },*/

// 判断是jdreact-core-lib.native.js文件
function is_jdreact_core_lib_native_file(ast,jsbundle_code) {
	const start = ast.start;
	const end = ast.end;
	const code = jsbundle_code.substring(start,end);
	const m = code.match(/get\s+JD[a-zA-Z0-9\_]+\(/g);
	if(m&&m.length>20){
		return true;
	}
}

// 只出现一次
function only_exist_once(list,jsbundle_code) {
	let once_list = [];
	for(let i=0; i<list.length; i++){
		const itm = list[i];
		const name = itm.name;
		const reg = new RegExp("\\b"+name+"\\b" , "g");
		const m = jsbundle_code.match(reg);
		if(m&&m.length<=1){
			once_list.push(itm);
		} else {
			console.log(name);
		}
	}
	return once_list;
}

function remove_jdreact_core_lib(jsbundle_folder){
	var all_files = file.getAllFilepathInDirSync(jsbundle_folder,function (fullpath,stat,filename) {
		if(filename.match(/\.jsbundle$/)){
			return true;
		}
	},true);

	if((!all_files)||(!all_files[0])){
		var error_msg = '没有找到.jsbundle文件';
		console.log(color.red(error_msg));
		return error_msg;
	}
	if(all_files.length>1){
		var error_msg = '找到多个.jsbundle文件';
		console.log(color.red(error_msg));
		return error_msg;
	}
	// 读取文件内容
	var js_code_filepath = all_files[0];
	var jsbundle_code = file.readFileSync(js_code_filepath);

	var ast = acorn.parse(jsbundle_code,{ranges:true});
	var body = ast.body;


// __d(...)的个数比例必须大于80%
	var percentage = count__d_call_percentage(ast);
	if (percentage < 0.80) {
		var error_msg = '文件内容可能和预期的不一致';
		console.log(error_msg);
		return error_msg;
	} else {
		//console.log('__d()比例=' + percentage);
	}

	var body = ast.body;
	var len = body.length;
	let jdreact_core_lib_common_files_list = [];
	let jdreact_core_lib_native_files_list = [];
	let jdreact_core_lib_common_file_ast , jdreact_core_lib_native_file_ast;
	let jdreact_core_lib_common_file_code , jdreact_core_lib_native_file_code;
	let jdreact_core_lib_common_file_widget_list , jdreact_core_lib_native_file_widget_list;


	let files_both_match = [];
	for(var i=0; i<len; i++){
		var itm_ast = body[i];
		if(!is__d_call(itm_ast)){
			continue;
		}
		var start = itm_ast.start;
		var end = itm_ast.end;
		var code = jsbundle_code.substring(start,end);
		const is_common = is_jdreact_core_lib_common_file(itm_ast,jsbundle_code);
		const is_native = is_jdreact_core_lib_native_file(itm_ast,jsbundle_code);

		if(is_common){
			jdreact_core_lib_common_files_list.push({
				ast:itm_ast,
				widget_list:is_common
			});
		}
		if(is_native){
			jdreact_core_lib_native_files_list.push({
				ast:itm_ast,
				widget_list:is_native
			});
		}
		if(is_common && is_native){
			files_both_match.push(itm_ast);
		}
	}

	const is_expected = (jdreact_core_lib_common_files_list.length===1) && (jdreact_core_lib_native_files_list.length===1) && (files_both_match.length===0);
	if(!is_expected){
		if(jdreact_core_lib_common_files_list.length===0){
			return '没有找到jdreact-core-lib.common.js对应的代码';
		}
		if(jdreact_core_lib_common_files_list.length>1){
			return '找到多个jdreact-core-lib.common.js对应的代码';
		}
		if(jdreact_core_lib_native_files_list.length===0){
			return '没有找到jdreact-core-lib.native.js对应的代码';
		}
		if(jdreact_core_lib_native_files_list.length>1){
			return '找到多个jdreact-core-lib.native.js对应的代码';
		}
		if(files_both_match.length>0){
			return '找到了'+files_both_match.length+'个文件，同时匹配jdreact-core-lib.common.js和jdreact-core-lib.native.js';
		}
		return 'Oh....Please ask the author why you can reach here.';
	} else {
		jdreact_core_lib_common_file_ast = jdreact_core_lib_common_files_list[0].ast;
		jdreact_core_lib_common_file_widget_list = jdreact_core_lib_common_files_list[0].widget_list;
		jdreact_core_lib_common_file_code = jsbundle_code.substring(jdreact_core_lib_common_file_ast.start,jdreact_core_lib_common_file_ast.end);


		jdreact_core_lib_native_file_ast = jdreact_core_lib_native_files_list[0].ast;
		jdreact_core_lib_native_file_widget_list = jdreact_core_lib_native_files_list[0].widget_list;
		jdreact_core_lib_native_file_code = jsbundle_code.substring(jdreact_core_lib_native_file_ast.start,jdreact_core_lib_native_file_ast.end);

	}
	//
	// write_comment_file('jdreact_core_lib_common_file_ast.json',jdreact_core_lib_common_file_ast);
	// write_comment_file('jdreact_core_lib_native_file_ast.json',jdreact_core_lib_native_file_ast);
	// write_comment_file('jdreact_core_lib_common_file_code.js',jdreact_core_lib_common_file_code.replace(/\)\,/g,'),\n'));
	// write_comment_file('jdreact_core_lib_native_file_code.js',jdreact_core_lib_native_file_code.replace(/\}\,/g,'},\n'));

	// 拆除common.js
	//write_comment_file('common_file_widget_list.json',jdreact_core_lib_common_file_widget_list);
	const list = only_exist_once(jdreact_core_lib_common_file_widget_list,jsbundle_code);
	//write_comment_file('common_file_widget_list_unuse.json',list);




	return true;


}

module.exports = remove_jdreact_core_lib;









